import { ExtractionTask, ExtractionResult, ParserConfig } from '../types';

export interface ParserOptions {
  includeComments: boolean;
  extractContext: boolean;
  maxDepth: number;
  ignorePatterns: string[];
  keyPatterns: string[];
  valuePatterns: string[];
  customRules: Array<{
    name: string;
    pattern: string;
    action: 'include' | 'exclude' | 'transform';
    params?: Record<string, any>;
  }>;
}

export interface ParseContext {
  filePath: string;
  task: ExtractionTask;
  config: ParserConfig;
}

export interface BaseParser {
  parse(content: string, context: ParseContext): Promise<ExtractionResult>;
}

export abstract class AbstractParser implements BaseParser {
  protected options: ParserOptions;

  constructor(options: ParserOptions) {
    this.options = options;
  }

  abstract parse(content: string, context: ParseContext): Promise<ExtractionResult>;

  /**
   * 验证内容是否匹配忽略模式
   * @param content 文件内容
   */
  protected shouldIgnore(content: string): boolean {
    return this.options.ignorePatterns.some(pattern => {
      const regex = new RegExp(pattern);
      return regex.test(content);
    });
  }

  /**
   * 验证键名是否匹配模式
   * @param key 键名
   */
  protected isValidKey(key: string): boolean {
    if (this.options.keyPatterns.length === 0) {
      return true;
    }
    return this.options.keyPatterns.some(pattern => {
      const regex = new RegExp(pattern);
      return regex.test(key);
    });
  }

  /**
   * 验证值是否匹配模式
   * @param value 值
   */
  protected isValidValue(value: string): boolean {
    if (this.options.valuePatterns.length === 0) {
      return true;
    }
    return this.options.valuePatterns.some(pattern => {
      const regex = new RegExp(pattern);
      return regex.test(value);
    });
  }

  /**
   * 应用自定义规则
   * @param content 内容
   */
  protected applyCustomRules(content: string): string {
    let result = content;
    for (const rule of this.options.customRules) {
      const regex = new RegExp(rule.pattern);
      switch (rule.action) {
        case 'include':
          if (!regex.test(result)) {
            result = '';
          }
          break;
        case 'exclude':
          if (regex.test(result)) {
            result = '';
          }
          break;
        case 'transform':
          result = result.replace(regex, rule.params?.replacement || '');
          break;
      }
    }
    return result;
  }

  /**
   * 提取上下文
   * @param content 文件内容
   * @param line 行号
   * @param column 列号
   */
  protected extractContext(content: string, line: number, column: number): string {
    if (!this.options.extractContext) {
      return '';
    }

    const lines = content.split('\n');
    const startLine = Math.max(0, line - 2);
    const endLine = Math.min(lines.length - 1, line + 2);

    const contextLines = lines.slice(startLine, endLine + 1);
    return contextLines.join('\n');
  }
} 